import { defineStore } from 'pinia'
import { store } from '../../index'
import { ProductApi } from '@/api/erp/product/product'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'

const { wsCache } = useCache('sessionStorage')

export interface ProductState {
  productMap: Map<number, any>
  isSetProduct: boolean
  lastUpdateTime: number
}

export const useProductStore = defineStore('erpProduct', {
  state: (): ProductState => ({
    productMap: new Map<number, any>(),
    isSetProduct: false,
    lastUpdateTime: 0
  }),
  getters: {
    getProductMap(): Map<number, any> {
      const productMap = wsCache.get(CACHE_KEY.ERP_PRODUCT_CACHE)
      if (productMap) {
        this.productMap = new Map(Object.entries(productMap).map(([k, v]) => [Number(k), v]))
        this.lastUpdateTime = wsCache.get(CACHE_KEY.ERP_PRODUCT_TIME) || 0
      }
      return this.productMap
    },
    getIsSetProduct(): boolean {
      return this.isSetProduct
    }
  },
  actions: {
    // 初始化加载所有产品（简化版）
    async setProductMap() {
      const productMap = wsCache.get(CACHE_KEY.ERP_PRODUCT_CACHE)
      const cacheTime = wsCache.get(CACHE_KEY.ERP_PRODUCT_TIME) || 0
      const now = Date.now()

      // 缓存有效期：5分钟
      if (productMap && (now - cacheTime) < 5 * 60 * 1000) {
        this.productMap = new Map(Object.entries(productMap).map(([k, v]) => [Number(k), v]))
        this.lastUpdateTime = cacheTime
        this.isSetProduct = true
        return
      }

      // 加载所有产品（简化列表）
      try {
        debugger
        const res = await ProductApi.getProductSimpleList()
        const productDataMap = new Map<number, any>()
        res.forEach((product: any) => {
          productDataMap.set(product.id, product)
        })

        this.productMap = productDataMap
        this.isSetProduct = true
        this.lastUpdateTime = now

        // 转换为普通对象存入缓存（Map无法直接序列化）
        const cacheObj = Object.fromEntries(productDataMap)
        wsCache.set(CACHE_KEY.ERP_PRODUCT_CACHE, cacheObj, { exp: 5 * 60 }) // 5分钟过期
        wsCache.set(CACHE_KEY.ERP_PRODUCT_TIME, now)
      } catch (error) {
        console.error('加载产品列表失败:', error)
        this.isSetProduct = false
      }
    },

    // 根据ID获取产品
    async getProductById(id: number) {
      if (!this.isSetProduct) {
        await this.setProductMap()
      }

      // 如果缓存中有，直接返回
      if (this.productMap.has(id)) {
        return this.productMap.get(id)
      }

      // 如果缓存中没有，动态加载单个产品
      try {
        const product = await ProductApi.getProduct(id)
        if (product) {
          this.productMap.set(id, product)
          // 更新缓存
          const cacheObj = Object.fromEntries(this.productMap)
          wsCache.set(CACHE_KEY.ERP_PRODUCT_CACHE, cacheObj, { exp: 5 * 60 })
        }
        return product
      } catch (error) {
        console.error('加载产品详情失败:', error)
        return null
      }
    },

    // 批量获取产品
    async getProductsByIds(ids: number[]) {
      if (!this.isSetProduct) {
        await this.setProductMap()
      }

      const products: any[] = []
      const missingIds: number[] = []

      // 先从缓存中获取
      ids.forEach(id => {
        if (this.productMap.has(id)) {
          products.push(this.productMap.get(id))
        } else {
          missingIds.push(id)
        }
      })

      // 加载缺失的产品
      if (missingIds.length > 0) {
        try {
          const promises = missingIds.map(id => ProductApi.getProduct(id))
          const results = await Promise.all(promises)
          results.forEach(product => {
            if (product) {
              this.productMap.set(product.id, product)
              products.push(product)
            }
          })
          // 更新缓存
          const cacheObj = Object.fromEntries(this.productMap)
          wsCache.set(CACHE_KEY.ERP_PRODUCT_CACHE, cacheObj, { exp: 5 * 60 })
        } catch (error) {
          console.error('批量加载产品失败:', error)
        }
      }

      return products
    },

    // 搜索产品（从缓存中搜索）
    searchProducts(keyword: string) {
      if (!this.isSetProduct) {
        this.setProductMap()
      }

      if (!keyword) return []

      const result: any[] = []
      const lowerKeyword = keyword.toLowerCase()

      this.productMap.forEach(product => {
        if (
          product.name?.toLowerCase().includes(lowerKeyword) ||
          product.barCode?.toLowerCase().includes(lowerKeyword) ||
          product.standard?.toLowerCase().includes(lowerKeyword)
        ) {
          result.push(product)
        }
      })

      return result
    },

    // 强制刷新产品数据
    async refreshProductMap() {
      wsCache.delete(CACHE_KEY.ERP_PRODUCT_CACHE)
      wsCache.delete(CACHE_KEY.ERP_PRODUCT_TIME)
      await this.setProductMap()
    },

    // 添加或更新单个产品到缓存
    updateProduct(product: any) {
      if (product && product.id) {
        this.productMap.set(product.id, product)
        // 更新缓存
        const cacheObj = Object.fromEntries(this.productMap)
        wsCache.set(CACHE_KEY.ERP_PRODUCT_CACHE, cacheObj, { exp: 5 * 60 })
      }
    },

    // 清空产品缓存(用于退出登录时重置)
    clearProductCache() {
      // 清空 Store 状态
      this.productMap = new Map<number, any>()
      this.isSetProduct = false
      this.lastUpdateTime = 0

      // 清空 SessionStorage 缓存
      wsCache.delete(CACHE_KEY.ERP_PRODUCT_CACHE)
      wsCache.delete(CACHE_KEY.ERP_PRODUCT_TIME)
    }
  }
})

export const useProductStoreWithOut = () => {
  return useProductStore(store)
}
